import { createStore } from 'vuex'
import {reqlogin} from '@api/login'
import {reqprofile} from '@api/profile'
import { reqdeleteprofile } from '../api/profile'
const Types={
  User:"user",
  ProfileInfo:'ProfileInfo',
  DeleteProfileInfo:'DeleteProfileInfo',
 
}

export default createStore({
  state: {
   token:localStorage.getItem('token')!==''?localStorage.getItem('token'):'',
   user:{},
   role:1,
   profileinfo:[]
  },
  mutations: {
    deletetoken(state){
      state.token=''
      localStorage.removeItem('token')
    },
    // 编辑
    editProfile(state,data){
      console.log("事件触发",data);
     state.profileinfo.splice(data.index,1,data.form)
    },
    // 新增
    addProfile(state,data){
      console.log("事件触发",data);
     state.profileinfo.splice(0,0,data)
    },
    [Types.User](state,userinfo){
      state.user=userinfo
    },
    [Types.ProfileInfo](state,profileinfo){
      state.profileinfo=profileinfo
    },
    [Types.DeleteProfileInfo](state,index){
     state.profileinfo.splice(index,1)
    },
    QueryProfileInfo(state,result){
      state.profileinfo=result
     },



  },
  actions: {

    //登录
   async loginaction({commit},info){
      const result=await reqlogin(info,{},{headers: {'Content-Type': 'application/x-www-form-urlencoded'},})
      localStorage.setItem("token",result.data.token)
      // 保存用户信息
      commit(Types.User,result.data.user)
     console.log("store获取的数据",result)
   return result

    },
    // 获取全部用户信息
   async getProfileInfo({commit}){
      const result =await reqprofile()
      commit(Types.ProfileInfo,result)
    },
    // 删除用户信息
    async deleteprofile({commit},data){
   const result= await reqdeleteprofile({_id:data._id},{headers: {'Content-Type': 'application/x-www-form-urlencoded'},})
   if (result) {
    commit(Types.DeleteProfileInfo,data.index)
   }
  


    }
    
  },
  modules: {
  }
})
